﻿using System.Linq;
using Fisharoo.DataAccess.Interfaces;
using System.ComponentModel.Composition;

namespace Fisharoo.DataAccess
{
    [Export(typeof(ITermRepository))]
    public class TermRepository : ITermRepository
    {
        private Connection conn;

        public TermRepository()
        {
            conn = new Connection();
        }

        public Term GetCurrentTerm()
        {
            using (FisharooDataContext dc = conn.GetContext())
            {
                Term term = (from t in dc.Terms
                            orderby t.CreateDate descending
                            select t).FirstOrDefault();
                return term;
                
            }
        }

        public void SaveTerm(Term term)
        {
            using (FisharooDataContext dc = conn.GetContext())
            {
                if (term.TermID > 0)
                {
                    dc.Terms.AddObject(term);
                }
                else
                {
                    dc.Terms.ApplyCurrentValues(term);
                }
                dc.SaveChanges();
            }
        }

        public void DeleteTerm(Term term)
        {
            using(FisharooDataContext dc = conn.GetContext())
            {
                dc.DeleteObject(term);
                dc.SaveChanges();
            }
        }
    }
}
